﻿var DATA={
	path:window.location.pathname
	,hostpath:'/'
	,datapath:'/'
	,hostpath:window.location.protocol+'//'+window.location.host
	,urlpath:getUrlpath()
	,guipath:getUrlpath()+'_GUI/'
	,nbipath:getUrlpath()+'_NBI/'
	,filename:getUrlFileName()
	,win:window.win||window.parent.curWin||null
	,lang:getRequest('lang')
	,session_id:getRequest('session_id') ? getRequest('session_id'): (window.top.DATA?window.top.DATA.session_id:null)
	,username:getRequest("username")
	,permission:getRequest("permission")?getRequest("permission").split(','):[] // 权限顺序：c，r，u，d
	,userid:getRequest("userid")
	,admin_domain:getRequest("admindomain")
	,super_user:getRequest("su")
	,permissions:{}			//记录权限列表
	,list_schema:null		//用于表格的schema
	,action_schema:null		//用于Action的schema
	,schema:null			//Schema数据 json  {primary_key,marked,columns} 用于表单
	,menu:null			//菜单数据 xml
	,customMenu:null		//自定义菜单json
	,getColumns:function(){		//获取列名
		return $('#grid')[0]?$('#grid')[0].grid.getColumns():null;
	}
	,getTotal:function(){		//获取总数据行数
		return $('#grid')[0]?$('#grid')[0].grid.getTotal():null;
	}
	,getSelected:function(){	//获取选中行的id 返回一个数组
		return $('#grid')[0]?$('#grid')[0].grid.getSelected():null;
	}
	,getSelectedValue:function(cols){	//获取选中行指定列的数值，输入一个数组，返回一个对象  {trid1:{col1:,col2:},trid2:{col1:,col2:}}
		return $('#grid')[0]?$('#grid')[0].grid.getSelectedValue(cols):null;
	}
	,getSelectedArray:function(cols){
		return $('#grid')[0]?$('#grid')[0].grid.getSelectedArray(cols):null;
	}
	,getGridParams:function(){
		return $('#grid')[0]?$('#grid')[0].grid.getParams():null;
	}
	,clearGridData:function(){	//刷新当前窗口数据表的函数
		return $('#grid')[0]?$('#grid')[0].grid.clearGridData():null;
	}
	,refreshGrid:function(){	//刷新当前窗口数据表的函数
		$('#SEARCH').click();
	}
	,report_data:null		//保存报表的__sum, __groupby, __count
	,refreshWin:null		//刷新当前窗口的函数
	,formCallback:null		//处理表单提交的函数
	,layout:[]			//纪录layout
};

var UserData={}

/*单击页面隐藏top菜单*/
$(function(){
	//if(window!==window.top){
		$(document).bind('mousedown',function(){
			window.top.$('.clickMenu > .hover').click().removeClass('hover');
		});
	//}
});




/*
屏蔽键盘
document.documentElement.onkeydown=function(event){
        var e=window.event||event;
        var t=e.srcElement||e.target;;
        if (e.keyCode==8&&t.tagName!="INPUT"&&t.tagName!="TEXTAREA"){return false;}
        if (e.keyCode==116||e.keyCode==122){return false;}
        if (e.altKey&& (e.keyCode==37||e.keyCode==39||e.keyCode==115)) {return false;}
        if (e.ctrlKey&& (e.keyCode==65||e.keyCode==70||e.keyCode==72||e.keyCode==69||e.keyCode==78||e.keyCode==82||e.keyCode==83||e.keyCode==87||e.keyCode==90|e.keyCode==115||e.keyCode==116)) {return false;}
        if (e.shiftKey&&(t.tagName == "A" ||e.keyCode==121 )){return false;}
        e.preventDefault();
      }
*/
//document.onselectstart=function(){return false;} 
//document.oncontextmenu=function (){return false;} 
//window.onbeforeunload=function () {return false;} 
    
//获取改变值的ID名称
function getNoChgValues(exp1,obj){
	var priArray= []
	$(exp1,obj).each(function(){
		if($(this).attr("origin_value") && $(this).val() != $(this).attr("origin_value")){
			priArray.push($(this).attr("id"));
		}
	})
	return priArray;
}

//置中窗口
function resizeWindow(w,h){
	window.DATA.win.resize(w,h);
	window.DATA.win.move();
};

//计算像素
function px(num){
	if(num<0||!num)num=0;
	return num.toString()+"px";
}

//是否数字
function isInt(x) {
	var y=parseInt(x);
	if (isNaN(y)) return false;
	return x==y && x.toString()==y.toString();
}

//转换为自然数
function toINT(v){
	var i=parseInt(v);
	if(isNaN(i)){return 1;}
	if(i<=1){return 1;}
	return Math.round (i);

}

//四舍五入保留小数位数
function round(v,n)
{
    v= Math.round (v*Math.pow(10,n))/Math.pow(10,n);
    return v;
}

//创建页面元素
function creatElement(p,n,Id,c){
	var ne=document.createElement(n);
	p.appendChild(ne);
	if(Id!="")ne.id=Id;
	if(c!="")ne.className=c;
	return ne;
}

//获取地址栏参数
function getRequest(name) { 
	var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
	var r = window.location.search.substr(1).match(reg);
	if (r!=null) return decodeURI(r[2]); return null; 
} 



//字符串转换xml对象 参见$.text2xml
function stringToXML(s, doc) {
	if (window.ActiveXObject) {
		doc = new ActiveXObject('Microsoft.XMLDOM');
		doc.async = 'false';
		doc.loadXML(s);
	}
	else
		doc = (new DOMParser()).parseFromString(s, 'text/xml');
	return (doc && doc.documentElement && doc.documentElement.tagName != 'parsererror') ? doc : null;
}



//xml对象转换字符串
function xmlToString(xml)   
{   
    if (window.ActiveXObject) {   
        return xml.xml;   
    } else {
        return (new XMLSerializer()).serializeToString(xml);   
    }   
}  


/*格式化时间为YYYY-MM-dd hh:mm:ss*/
function formatDateTime(dt){
	var y=dt.getFullYear();
	var m=dt.getMonth()+1;
	var d=dt.getDate();
	var h=dt.getHours();
	var M=dt.getMinutes();
	var s=dt.getSeconds();
	if (m<10)m='0'+m;
	if (d<10)d='0'+d;
	if (h<10)h='0'+h;
	if (M<10)M='0'+M;
	if (s<10)s='0'+s;
	return y+'-'+m+'-'+d+' '+h+':'+M+':'+s
}


/*格式化秒数为小时数*/
function formatTime(s){
	var m=s/60;
	var h=m/60;
	m=parseInt(m);
	h=parseInt(h);
	if(s>=60)s=s%60;
	if(m>=60)m=m%60;
	if(s<10)s="0"+s;
	if(m<10)m="0"+m;
	if(h<10)h="0"+h
	return h+":"+m+":"+s;
}


/*格式化磁盘容量*/
function formatBytes(bytes) {
	if (bytes==0) return 0;
    var s = ['bytes', 'kb', 'MB', 'GB', 'TB', 'PB'];
    var e = Math.floor(Math.log(bytes)/Math.log(1024));
    return (bytes/Math.pow(1024, Math.floor(e))).toFixed(2)+" "+s[e];
}


/*验证文件名*/
function validateFileName(s){
	if(!s)return false;
	if(s.replace(/\s/g,'')=="")return false;
	if(/.*[\\\/:\*\?"<>|].*/.exec(s) || /^\./.exec(s) ){
		alert ($.l10n.__('alert_invalidfilename') );
		return false
	}
	return true;
}



/*对象排序*/
function compareObject(n) {
	return function (object1, object2) {
		var value1 = object1[n]||$(object1).attr(n);
		var value2 = object2[n]||$(object2).attr(n);
		if (value2 > value1) {
			return -1;
		}else if (value2 < value1) {
			return 1;
		}else {
			return 0;
		}
	}
} 


/*json到字符串*/
function jsonToString(obj){  
	switch(typeof(obj)){  
		case 'string':  
			return '"' + obj.replace(/(["\\])/g, '\\$1') + '"';  
	 	case 'array':  
	   		return '[' + obj.map(THIS.jsonToString).join(',') + ']';  
		case 'object':  
		 if(obj instanceof Array){
			var strArr = [];  
			var len = obj.length;  
			for(var i=0; i<len; i++){  
				strArr.push(jsonToString(obj[i]));  
			}  
			 return '[' + strArr.join(',') + ']';  
		}else if(obj==null){  
		   return 'null';  
		}else{  
			var string = [];  
			for (var property in obj) string.push(jsonToString(property) + ':' + jsonToString(obj[property]));  
			return '{' + string.join(',') + '}';  
		 }  
		case 'number':  
			return obj;  
		case false:  
	   		return obj;  
		}  
}




/*翻译*/
function loadLang(option){
	if(!option)option={}; 
	//var lang=option.lang||window.top.DATA.lang||window.navigator.systemLanguage || window.navigator.language ;
	//lang=lang.replace('_','-').toLowerCase();
	var lang = 'zh-cn';
	var el=(option.el)?$('[domain=l10n]',option.el):$('[domain=l10n]');
	
	var path=option.path||'';
 	window.top.DATA.lang=lang;
 	window.DATA.lang=lang;
	el.each(function(){
		try{
			if($(this).attr('msgid'))$(this).attr('msgid',$(this).attr('msgid').toLowerCase());
			if($(this).attr('msgid_title'))$(this).attr('msgid_title',$(this).attr('msgid_title').toLowerCase());
		}catch(e){}
	});
	el.l10n({
		dir: window.DATA.guipath+"Languages"
		,lang: lang
	});
	/*el.l10n({
		dir: window.DATA.guipath+"Languages"
		,lang: lang
	});*/
	//$("select#lang option[value='"+lang+"']").attr("selected","selected");

}


/*加密*/
/**
function Crypt(pw,modulus,public){
	var rsa = new RSAKey();
	rsa.setPublic(modulus,public);
	var p=rsa.encrypt(pw);
	//var res = hex2b64(p);
	return p;
}
**/

/*获取url路径*/
function getUrlpath(){
	var p=(window.location.pathname);
	if(/\/_GUI\/$/.test(p)){
		p=p.replace('/_GUI/','/');
		return p;
	}
	if(/\/$/.test(p))return p;
	p=p.split('/');
	p.pop();p.pop();
	p=p.join('/')+'/';
	return p;
}

/*从url获取路径名称*/
function getUrlFileName(){
	var p =window.location.pathname;
	var as = p.split('/');
	var bs = as[as.length-1].split('.');
	return bs[0];
}




/*获取IP范围*/
function getIPRange(ip){
	var to=ip.split('.');
	for(var i=0,l=to.length;i<l;i++){
		if(to[i]==='0'||to[i]===0)to[i]=255;
	}
	return to.join('.');
}


/*转换颜色*/
function RGBToHex(rgbString) {	
	var parts = rgbString.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
	delete (parts[0]);
	for (var i = 1; i <= 3; ++i) {
		parts[i] = parseInt(parts[i]).toString(16);
		if (parts[i].length == 1) parts[i] = '0' + parts[i];
	}
	var hexString = parts.join('');
	return hexString;
};



//替换第N个某字符
function replaceN(o) {
	//{str:'' find:'' changeto:'' nth:}
	var r = new RegExp(o.find, "gi"); 
	var i=0;
	return o.str.replace(r,function($0,$1,$2) {
		i++;
		if(i===o.nth)return o.changeto;
		else return o.find;
	});
}


/*Grid表格处理*/
(function($){
$.addGrid = function(t,o){
	var g={
		init:function(){
			o = $.extend({
				column:[]
				,row:[]
			},o); 
			$(t).html('<div id="COLUMN"><table border="1" cellpadding="0" cellspacing="0"><thead><tr></tr></thead></table></div><div id="ROW"><table border="1" cellpadding="0" cellspacing="0"><tbody></tbody></table></div><div id="TABLE"><table border="1" cellpadding="0" cellspacing="0"><tbody></tbody></table></div>');
			for(var i=0,l=o.column.length;i<l;i++){
				$('#COLUMN tr',t).append('<th h="'+i+'" value="'+o.column[i].value+'">'+o.column[i].text+'</th>');
			}
			for(var i=0,l=o.row.length;i<l;i++){
				$('#ROW tbody').append('<tr v="'+i+'"><th v="'+i+'" value="'+o.row[i].value+'" >'+o.row[i].text+'</th></tr>');
				var tr=document.createElement('tr');
				$(tr).attr('v',i);
				var from_id=o.row[i].value;
				for(var j=0,ll=o.column.length;j<ll;j++){
					var to_id=o.column[j].value;
					$(tr).append('<td h="'+j+'" v="'+i+'" from_to="'+from_id+'_'+to_id+'"></td>');
					$('#TABLE tbody',t).append(tr);
				}
			}
			$('#ROW th,#COLUMN th',t).click(function(){
				$('td.selected,th.selected',t).removeClass('selected');
				$(this).addClass('selected');
				if($(this).attr('v'))$('#TABLE td[v="'+$(this).attr('v')+'"]',t).addClass('selected');
				if($(this).attr('h'))$('#TABLE td[h="'+$(this).attr('h')+'"]',t).addClass('selected');
				
			});
			$('#TABLE td',t).click(function(){
				$('td.selected,th.selected',t).removeClass('selected');
				$(this).addClass('selected');
			});
			$('#COLUMN th:last').after('<th></th>');
			$('#ROW tr:last').after('<tr><th></th></tr>');
			$('th,td',t).wrapInner('<div/>');
			$(t).append('<div id="CORNER"></div>');	
		}

		,layout:function(){
			var $C=$('#COLUMN',t);
			var $R=$('#ROW',t);
			var $T=$('#TABLE',t);
			var $Cn=$('#CORNER',t);
			var $Ct=$('#COLUMN table',t);
			var $Rt=$('#ROW table',t);
			var $Tt=$('#TABLE table',t);
			var i=1; 
			$('th > div,td > div',t).css({width:'100%',height:'100%'});
			$('#COLUMN th',t).each(function(){
				var $td=$('#TABLE tr > td:nth-child('+i+')');
				var w0=$(this).width();
				var w1=$td.width();
				var w=Math.max(w0,w1);
				$('> div',this).width(w);
				$('> div',$td).width(w);
				i++;
			});
			i=1;
			$('#ROW th',t).each(function(){
				var $td=$('#TABLE tr:nth-child('+i+') > td '); 
				var h0=$(this).height();
				var h1=$td.height();
				var h=Math.max(h0,h1);
				$('> div',this).height(h);
				$('> div',$td).height(h);
				i++;
			});
			var w=$Rt.width();
			var h=$Ct.height();
			$Cn.css({width:w-1,height:h-1});
			$('th:last > div',$Ct).width(100000);
			$('th:last > div',$Rt).height(100000);
			$T.scroll(function(){
				$C.scrollLeft(this.scrollLeft);
				$R.scrollTop(this.scrollTop);
			});
			$(window).unbind('resize',g.resize).resize(g.resize).resize();
		}

		,resize:function(){
			var $C=$('#COLUMN',t);
			var $R=$('#ROW',t);
			var $T=$('#TABLE',t);
			var $Ct=$('#COLUMN table',t);
			var $Rt=$('#ROW table',t);
			var w=$Rt.width();
			var h=$Ct.height(); 
			window.setTimeout(function(){
				$T.css({
					left:w
					,top:h
					,width:$(t).width()-w
					,height:$(t).height()-h
				});
				$C.css({
					left: w
					,width:$(t).width()-w
				});
				$R.css({
					top: h
					,height:$(t).height()-h
				});
			},500);
		}

		,set:function(from,to,html){
			$('#TABLE td[from_to="'+from+'_'+to+'"] > div',t).html(html);
			g.layout();
		}

		,clear:function(){
			$('#TABLE td > div',t).empty();
		}
		
	};
	t.grid=g;
	g.init();
	return g;
}
$.fn.grid = function(o) {
	return this.each( function() {
		$.addGrid(this,o);
	});

}; 
})(jQuery);





//Jquery 的Cookie
jQuery.cookie = function (key, value, options) {    
    if (arguments.length > 1 && String(value) !== "[object Object]") {
        options = jQuery.extend({}, options);

        if (value === null || value === undefined) {
            options.expires = -1;
        }

        if (typeof options.expires === 'number') {
            var days = options.expires, t = options.expires = new Date();
            t.setDate(t.getDate() + days);
        }
        
        value = String(value);
        
        return (document.cookie = [
            encodeURIComponent(key), '=',
            options.raw ? value : encodeURIComponent(value),
            options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
            options.path ? '; path=' + options.path : '',
            options.domain ? '; domain=' + options.domain : '',
            options.secure ? '; secure' : ''
        ].join(''));
    }

    // key and possibly options given, get cookie...
    options = value || {};
    var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent;
    return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
};


//Combobox Widget
(function( $ ) {
	if(typeof($.widget)!=="function")
		return;
	$.widget( "ui.combobox", {
		_create: function() {
			var self = this,
				select = this.element.hide(),
				selected = select.children( ":selected" ),
				value = selected.val() ? selected.text() : "";
			var input = this.input = $( "<input>" )
				.insertAfter( select )
				.val( value )
				.autocomplete({
					delay: 0,
					minLength: 0,
					source: function( request, response ) {
						var matcher = new RegExp( $.ui.autocomplete.escapeRegex(request.term), "i" );
						response( select.children( "option" ).map(function() {
							var text = $( this ).text();
							if ( this.value && ( !request.term || matcher.test(text) ) )
								return {
									label: text.replace(
										new RegExp(
											"(?![^&;]+;)(?!<[^<>]*)(" +
											$.ui.autocomplete.escapeRegex(request.term) +
											")(?![^<>]*>)(?![^&;]+;)", "gi"
										), "<strong>$1</strong>" ),
									value: text,
									option: this
								};
						}) );
					},
					select: function( event, ui ) {
						ui.item.option.selected = true;
						self._trigger( "selected", event, {
							item: ui.item.option
						});
					},
					change: function( event, ui ) {
						if ( !ui.item ) {
							var matcher = new RegExp( "^" + $.ui.autocomplete.escapeRegex( $(this).val() ) + "$", "i" ),
								valid = false;
							select.children( "option" ).each(function() {
								if ( $( this ).text().match( matcher ) ) {
									this.selected = valid = true;
									return false;
								}
							});
							if ( !valid ) {
								// remove invalid value, as it didn't match anything
								$( this ).val( "" );
								select.val( "" );
								input.data( "autocomplete" ).term = "";
								return false;
							}
						}
					}
				})
				.addClass( "ui-widget ui-widget-content ui-corner-left" );

			input.data( "autocomplete" )._renderItem = function( ul, item ) {
				return $( "<li></li>" )
					.data( "item.autocomplete", item )
					.append( "<a>" + item.label + "</a>" )
					.appendTo( ul );
			};

			this.button = $( "<button>&nbsp;</button>" )
				.attr( "tabIndex", -1 )
				.attr( "title", "Show All Items" )
				.insertAfter( input )
				.button({
					icons: {
						primary: "ui-icon-triangle-1-s"
					},
					text: false
				})
				.removeClass( "ui-corner-all" )
				.addClass( "ui-corner-right ui-button-icon" )
				.click(function() {
					// close if already visible
					if ( input.autocomplete( "widget" ).is( ":visible" ) ) {
						input.autocomplete( "close" );
						return;
					}

					// pass empty string as value to search for, displaying all results
					input.autocomplete( "search", "" );
					input.focus();
				});
		},

		destroy: function() {
			this.input.remove();
			this.button.remove();
			this.element.show();
			$.Widget.prototype.destroy.call( this );
		}
	});
})( jQuery );


//xml 2 object
(function($){ 
	$.extend({  
		xml2json: function(xml, extended) {
			if(!xml) return {}; 
  			function parseXML(node, simple){
    				if(!node) return null;
    				var txt = '', obj = null, att = null;
    				var nt = node.nodeType, nn = jsVar(node.localName || node.nodeName);
    				var nv = node.text || node.nodeValue || '';
   				if(node.childNodes){
     					if(node.childNodes.length>0){      
      						$.each(node.childNodes, function(n,cn){
      							var cnt = cn.nodeType, cnn = jsVar(cn.localName || cn.nodeName);
       							var cnv = cn.text || cn.nodeValue || '';
       							if(cnt == 8){
       								 return; 
       							}
      							else if(cnt == 3 || cnt == 4 || !cnn){
        							if(cnv.match(/^\s+$/)){
									return;
								};
								txt += cnv.replace(/^\s+/,'').replace(/\s+$/,'');
							}
							else{
								obj = obj || {};
								if(obj[cnn]){
									if(!obj[cnn].length) obj[cnn] = myArr(obj[cnn]);
									obj[cnn][ obj[cnn].length ] = parseXML(cn, true/* simple */);
									obj[cnn].length = obj[cnn].length;
								}
								else{
         								obj[cnn] = parseXML(cn);
								};
							};
						});
					};
    				};
   				if(node.attributes){
					if(node.attributes.length>0){
						att = {}; obj = obj || {};
						$.each(node.attributes, function(a,at){
							var atn = jsVar(at.name), atv = at.value;
							att[atn] = atv;
							if(obj[atn]){
								if(!obj[atn].length) obj[atn] = myArr(obj[atn]);//[ obj[ atn ] ];
								obj[atn][ obj[atn].length ] = atv;
								obj[atn].length = obj[atn].length;
       							}
							else{
								obj[atn] = atv;
							};
						});
					};
				};
				if(obj){
					obj = $.extend( (txt!='' ? new String(txt) : {}),/* {text:txt},*/ obj || {}/*, att || {}*/);
					txt = (obj.text) ? (typeof(obj.text)=='object' ? obj.text : [obj.text || '']).concat([txt]) : txt;
					if(txt) obj.text = txt;
					txt = '';
				};
				var out = obj || txt;
				if(extended){
					if(txt) out = {};
					txt = out.text || txt || '';
					if(txt) out.text = txt;
					if(!simple) out = myArr(out);
				};
				return out;
			};
			var jsVar = function(s){ return String(s || '').replace(/-/g,"_"); };
			var isNum = function(s){ return (typeof s == "number") || String((s && typeof s == "string") ? s : '').test(/^((-)?([0-9]*)((\.{0,1})([0-9]+))?$)/); };
			var myArr = function(o){
				if(!o.length) o = [ o ]; o.length=o.length;
				return o;
			};

			if(typeof xml=='string') xml = $.text2xml(xml);
			if(!xml.nodeType) return;
			if(xml.nodeType == 3 || xml.nodeType == 4) return xml.nodeValue;
			var root = (xml.nodeType == 9) ? xml.documentElement : xml;
			var out = parseXML(root, true);
			xml = null; root = null;
			return out;
		},
  

		text2xml: function(str) {
			var out;
  			try{
				var xml = ($.browser.msie)?new ActiveXObject("Microsoft.XMLDOM"):new DOMParser();
				xml.async = false;
			}catch(e){ throw new Error("XML Parser could not be instantiated") };
			try{
				if($.browser.msie) out = (xml.loadXML(str))?xml:false;
				else out = xml.parseFromString(str, "text/xml");
			}catch(e){ throw new Error("Error parsing XML string") };
			return out;
		}
		
	});

})(jQuery);


